<template>
  <Container class="bargain-rules">
    <div class="bg-light">
      <div class="container-title">限购设置</div>
      <Form :label-width="170" :rules="rule" ref="form" :model="$store.state.bargain.form">
        <Row class="pr">
          <Col span="24">
            <div class="box">
              <FormItem label-width="20">
                <RadioGroup v-model="$store.state.bargain.form.isCurrencyNum">
                  <Radio label='0' :disabled="isShelf !== 'UNDER'">通用门店限购数量</Radio>
                  <Radio label='1' :disabled="isShelf !== 'UNDER'">按门店类型限购数量(不打勾则不参与活动)</Radio>
                </RadioGroup>
              </FormItem>
            </div>
          </Col>
        </Row>
        <Row>
          <Col span="8">
            <FormItem label="通用门店限购数量" label-width="145" v-if="bargainIsCurrencyNum">
              <InputNumber :disabled="isShelf !== 'UNDER'" :max="999999" :min="1"  v-model="$store.state.bargain.form.limitNum" style="width:100%"></InputNumber>
            </FormItem>
          </Col>
        </Row>
        <Row class="pr" v-if="!bargainIsCurrencyNum">
          <Col span="8" :offset="(index + 1 ) % 2 === 0 ? 8 : ''" :pull="(index + 1 ) % 2 === 0 ? 8 : ''" v-for="(item, index) of $store.state.bargain.form.list" :key="index">
            <div class="flex-start">
              <Checkbox class="info" v-model="item.isChecked" :disabled="isShelf !== 'UNDER'">{{item.name}}</Checkbox>
              <InputNumber placeholder="请输入规格限购" :max="999999" :min="1" v-model="item.num" :disabled="!item.isChecked || isShelf !== 'UNDER'" style="width:50%" ></InputNumber>
              <InputNumber placeholder="请输入总量限购" :max="999999" :min="1" v-model="item.totalNum" :disabled="!item.isChecked || isShelf !== 'UNDER'" style="width:50%" ></InputNumber>
            </div>
          </Col>
        </Row>
      </Form>
      <div class="container-title">
        <div>
          例外设置<span class="font-red normal pl">注意：例外门店限购优先级大于活动内限购总量</span>
        </div>
      </div>
      <div class="mb20 pl20">
        <RadioGroup v-model="$store.state.bargain.form.isStoreSet">
          <Radio label='0' :disabled="isShelf !== 'UNDER'">按门店设置</Radio>
          <Radio label='1' :disabled="isShelf !== 'UNDER'">按经销商设置</Radio>
          <Radio label='2' :disabled="isShelf !== 'UNDER'">按规格设置</Radio>
        </RadioGroup>
      </div>
      <storeList ref="storeEdit" v-show="$store.state.bargain.form.isStoreSet == 0"></storeList>
      <distributor ref="distributorEdit" v-show="$store.state.bargain.form.isStoreSet == 1"></distributor>
      <SizeList ref="sizeList" v-show="$store.state.bargain.form.isStoreSet == 2"></SizeList>
    </div>
    <div class="container-footer bg-white" slot="footer">
      <Button size="large"  @click="onCancel">修改促销</Button>
      <Button class="ml" size="large" type="primary" @click="onPostExceptional">下一步</Button>
    </div>
    <Loader :status="status" @refresh="getDetailData"></Loader>
  </Container>
</template>
<script>
import { mapGetters } from 'vuex'
import storeList from './edit/StoreListItem'
import distributor from './edit/DistributorListItem'
import SizeList from './edit/SizeListItem'
export default {
  components: {
    storeList,
    distributor,
    SizeList
  },
  data() {
    return {
      isShelf: 'UNDER',
      status: 'pass'
    }
  },
  mounted() {
    this.getDetailData()
    this.getStoreTypeData()
    this.id && this.$store.dispatch("getShelfStatus", this.id).then(data => {
      this.isShelf = data
    })
  },
  methods: {
    getDetailData() {
      this.loading = true
      this.status = 'loading'
      this.$ajaxGet(`/activity/factory_info/detail/${this.$route.query.id}`).then(data => {
        this.loading = false
        this.status = 'pass'
        this.$store.commit('getBargainDetail', data)
        this.loading = false
      }).catch(data => {
        this.loading = false
        this.status = 'error'
      })
    },
    getStoreTypeData() {
      this.$store.dispatch('getStoreType').then(res => {
        this.$store.commit('setBargainStoreList', res)
      })
    },
    onPostExceptional() {
      this.loading = true
      if (this.validateStoreList) {
        alert(this.validateStoreList)
        return
      }
      this.status = 'loading'
      let params = {
        activityId: this.$route.query.id,
        commonLimitNumber: this.$store.state.bargain.form.limitNum ? this.$store.state.bargain.form.limitNum : '',
        exceptionalTypeEnum: this.exceptionalTypeEnum,
        limitTypeEnum: this.limitTypeEnum,
        storeTypeLimitNumberDTOList: this.limitTypeEnum == 'STORE_TYPE' ? this.storeTypeLimitNumberDTOList : []
      }
      this.loading = false
      this.$jsonPost(`/activity/factory_info/edit_exceptional`, params).then(data => {
        this.status = 'pass'
        this.loading = false
        this.$Notice.success({
          title: "工厂活动例外限购信息修改成功",
        })
        this.$router.push({name: 'sales/bargain/list', query: {id: this.$route.query.id}})
      }).catch(error => {
        this.status = 'pass'
      })
    },
    onCancel() {
      this.$router.push({name: 'sales/bargain/rules', query: {id: this.$route.query.id}})
    }
  },
  computed: {
    ...mapGetters([
      'bargainIsCurrencyNum',
      'barginIsStore',
      'storeTypeLimitNumberDTOList'
    ]),
    limitTypeEnum() {
      return this.$store.state.bargain.form.isCurrencyNum == '0' ? 'GENERAL_STORE' : 'STORE_TYPE' 
    },
    exceptionalTypeEnum() {
      let typeEnum = ''
      if (this.$store.state.bargain.form.isStoreSet == '0') typeEnum = 'STORE'
      if (this.$store.state.bargain.form.isStoreSet == '1') typeEnum = 'DISTRIBUTOR'
      if (this.$store.state.bargain.form.isStoreSet == '2') typeEnum = 'PRODUCT'
      return typeEnum
    },
    validateStoreList() {
      // 遍历所有被选中的元素-并且都有数据（判断是否第二个的值大于第一个值）
      // 把这些异常信息放在一个数组里
      // 拿出第一个异常信息（如果没有就不提示，有就拿出第一个）
      // 并且必须是按门店类型限购数量
      let errorList = []
      this.$store.state.bargain.form.list.forEach(item => {
        if (this.$store.state.bargain.form.isCurrencyNum == '1') {
          if (item.isChecked) {
            // 第一个值必填
            if (!item.num) {
              errorList.push(item.name + '规格限购不能为空')
            }
            if (item.isChecked && item.num && item.totalNum) { // 当两个值都有的情况下
              if (item.num > item.totalNum) {
                errorList.push(item.name + '总量限购必须大于等于规格限购')
              }
            }
          }
        } 
      })
      if (errorList.length) {
        return errorList[0]
      }
    }
  }
}
</script>